﻿using amis6_api.Common;
using amis6_api.Model;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace amis6_api.Utils
{
    public class GetOrderByStr
    {
        public static String GetStr(Guid fmtId)
        {
            StringBuilder orderBy = new StringBuilder("order by ");
            var conn = DbFactory.Db();
            var fieldRuleList = conn.Query<FieldRule>("Select a.*,b.Field_Name,b.Field_CnName from t_FieldRule a left join t_Data_Fields b on a.Field_ID=b.Field_ID where a.FMT_ID=@fmt_id and a.FR_RuleType='orderby';", new { fmt_id = fmtId }).ToList().OrderBy(a => a.FR_Rule);
            if (fieldRuleList.Any())
            {
                foreach (var item in fieldRuleList)
                {
                    string rule = "asc,";
                    if (!string.IsNullOrEmpty(item.FR_Remark))
                    {
                        rule = "desc,";
                    }
                    orderBy.Append($"[{item.Field_Name}]" + " " + rule + " ");
                }
                orderBy = orderBy.Remove(orderBy.Length - 2, 1);
            }
            else
            {
                orderBy.Append("CreateDateTime asc ");
            }
            return orderBy.ToString();
        }

        public static String GetStrFileAttachList(Guid fmtId)
        {
            StringBuilder orderBy = new StringBuilder("order by ");
            var conn = DbFactory.Db();
            var fieldRuleList = conn.Query<FieldRule>("Select a.*,b.Field_Name,b.Field_CnName from t_FieldRule a left join t_Data_Fields b on a.Field_ID=b.Field_ID where a.FMT_ID=@fmt_id and a.FR_RuleType='orderby';", new { fmt_id = fmtId }).ToList().OrderBy(a => a.FR_Rule);
            if (fieldRuleList.Any())
            {
                foreach (var item in fieldRuleList)
                {
                    string rule = "asc,";
                    if (!string.IsNullOrEmpty(item.FR_Remark))
                    {
                        rule = "desc,";
                    }
                    orderBy.Append($"[{item.Field_Name}]" + " " + rule + " ");
                }
                orderBy = orderBy.Remove(orderBy.Length - 2, 1);
            }
            else
            {
                orderBy.Clear();
            }
            return orderBy.ToString();
        }
    }
}
